﻿namespace NFakeMail.Example
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Net.Mail;
    using System.Threading;

    internal class Program
    {
        private const int SmtpServerPort = 10025;

        private static void Main(string[] args)
        {
            using (var fakeSmtpServer = new FakeSmtpServer(SmtpServerPort))
            {
                InvokeCodeThatSendsEmail();

                // Verifies that two messages are received in the next five seconds
                var messages = fakeSmtpServer.WaitForMessages(count: 2, timeout: 5000);

                // Verifies the message sender
                Debug.Assert(messages.All(m => m.From.Address == "me@me.com"));
            }

            using (var fakeSmtpServer = new FakeSmtpServer(SmtpServerPort))
            {
                InvokeCodeThatSendsEmailWithAttachment();

                // Verifies that one message is received in the next five seconds
                var message = fakeSmtpServer.WaitForMessage(timeout: 5000);

                // Verifies the message subject and intended recipient
                Debug.Assert(message.Subject == "S3");
                Debug.Assert(message.Recipients.Any(m => m.Address == "you@you.com"));
            }

            Thread.Sleep(5000);
        }

        private static void InvokeCodeThatSendsEmailWithAttachment()
        {
            using (var smtpClient = new SmtpClient("localhost", SmtpServerPort))
            {
                var from = new MailAddress("me@me.com", "Me");
                var to = new MailAddress("you@you.com", "You");

                var message = new MailMessage(from, to)
                {
                    Subject = "S3",
                    Body = "...",
                };

                var data = new MemoryStream(new byte[] { (byte)'A', (byte)'B' });

                message.Attachments.Add(new Attachment(data, "Attachment.txt"));

                smtpClient.Send(message);
            }
        }

        private static void InvokeCodeThatSendsEmail()
        {
            using (var smtpClient = new SmtpClient("localhost", SmtpServerPort))
            {
                smtpClient.Send("me@me.com", "you@you.com", "S1", ".");

                smtpClient.Send("me@me.com", "you@you.com", "S2", "..");
            }
        }
    }
}
